<template>
    <div class="d-i-b" style="width: 200px">
    <el-select
      :title="multiple? optionData.name : ''"
      ref="select"
      :value="value"
      placeholder="请选择"
      size="mini"
      clearable
      :disabled="disabled"
      :filterable="filterable"
      :filter-method="filterMethod"
      style="width: 200px;"
      @clear="clear"
      @visible-change="visibleChange"
    >
      <el-option
        ref="option"
        class="tree-select__option"
        :value="optionData.id"
        :label="optionData.name"
      >
        <el-tree
          ref="tree"
          class="tree-select__tree"
          :class="`tree-select__tree--${multiple ? 'checked' : 'radio'}`"
          :node-key="nodeKey"
          :data="data"
          :props="props"
          :check-strictly="true"
          :default-expanded-keys="expandedKeys"
          :show-checkbox="multiple"
          :highlight-current="!multiple"
          :expand-on-click-node="multiple"
          :filter-node-method="filterNode"
          @node-click="handleNodeClick"
          @check-change="handleCheckChange"
        ></el-tree>
      </el-option>
    </el-select>
    </div>
  </template>

<script>
export default {
  name: 'TreeSelect',
  props: {
    // v-model绑定
    value: {
      type: [String, Number],
      default: ''
    },
    multiple: {
      type: Boolean,
      default: false
    },
    // 树形的数据
    data: {
      type: Array,
      default: function () {
        return []
      }
    },
    // 每个树节点用来作为唯一标识的属性
    nodeKey: {
      type: [String, Number],
      default: 'id'
    },
    filterable: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    // tree的props配置
    props: {
      type: Object,
      default: function () {
        return {
          label: 'label',
          children: 'children'
        }
      }
    },
    url: Function
  },
  data () {
    return {
      optionData: {
        id: '',
        name: ''
      },
      formData: {
        pageIndex: 0,
        pageSize: 50,
        totalPage: 0
      },
      expandedKeys: [],
      filterFlag: false,
      fetchUrl: null
    }
  },
  watch: {
    value: {
      handler (val) {
        if (!this.isEmpty(this.data)) {
          this.init(val)
        }
      },
      immediate: true
    },
    data: {
      handler (val) {
        if (!this.isEmpty(val)) {
          this.init(this.value)
        }
        // 我这里默认展开一级, 指定几级就往里遍历几层取到 id 就可以了
        this.data.forEach((item, index) => {
          if (index === 0) { this.expandedKeys.push(item.id) }
        })
      },
      immediate: true
    }
  },
  mounted () {
    this.fetchUrl = this.url
    this.getList()
  },
  created () {},
  methods: {
    // 根据后台接口组装Data数据
    getList () {
      if (typeof this.fetchUrl !== 'function') return
      if (this.formData.pageIndex === 0 || this.formData.pageIndex < this.formData.totalPage) {
        const query = {
          criteria: { page: this.formData.pageIndex, size: this.formData.pageSize }
        }
        this.fetchUrl()(query).then(res => {
          if (res.content instanceof Array) {
            this.$set(this.formData, 'totalPage', res.totalPages)
            const result = res.content.map(item => {
              return { ...item, label: item[this.labelKey], value: item[this.valueKey] }
            })
            if (this.formData.pageIndex === 0 && this.selectedCode) {
              const hasItemAtFront = result.findIndex(m => m[this.valueKey] === this.selectedCode)
              if (hasItemAtFront !== -1) {
                this.list = []
              }
            }
            console.log(result)
            // this.data = this.data.concat(result)
            // console.log(this.data.concat(result))
          }
        })
      }
    },
    // 是否为空
    isEmpty (val) {
      for (const key in val) {
        return false
      }
      return true
    },
    handleNodeClick (data) {
      if (this.multiple) {
        return
      }
      this.$emit('input', data[this.nodeKey])
      this.$refs.select.visible = false
    },
    handleCheckChange () {
      const nodes = this.$refs.tree.getCheckedNodes()
      const value = nodes.map((item) => item[this.nodeKey]).join(',')
      this.$emit('input', value)
    },
    init (val) {
      // 多选
      if (this.multiple) {
        const arr = val.toString().split(',')
        this.$nextTick(() => {
          this.$refs.tree.setCheckedKeys(arr)
          const nodes = this.$refs.tree.getCheckedNodes()
          this.optionData.id = val
          this.optionData.name = nodes
            .map((item) => item[this.props.label])
            .join(',')
        })
      } else {
        // 单选
        val = val === '' ? null : val
        this.$nextTick(() => {
          this.$refs.tree.setCurrentKey(val)
          if (val === null) {
            return
          }
          const label = this.props.label || 'name'
          const node = this.$refs.tree.getNode(val)
          this.optionData.id = val
          this.optionData[label] = node.label
          this.optionData.name = node.label
        })
      }
    },
    visibleChange (e) {
      if (e) {
        const tree = this.$refs.tree
        this.filterFlag && tree.filter('')
        this.filterFlag = false
        let selectDom = null
        if (this.multiple) {
          selectDom = tree.$el.querySelector('.el-tree-node.is-checked')
        } else {
          selectDom = tree.$el.querySelector('.is-current')
        }
        setTimeout(() => {
          this.$refs.select.scrollToOption({ $el: selectDom })
        }, 0)
      }
    },
    clear () {
      this.$emit('input', '')
    },
    filterMethod (val) {
      this.filterFlag = true
      this.$refs.tree.filter(val)
    },
    filterNode (value, data) {
      if (!value) return true
      const label = this.props.label || 'name'
      return data[label].indexOf(value) !== -1
    }
  }
}
</script>

  <style lang="scss">
  .tree-select__option {
    &.el-select-dropdown__item {
      height: auto;
      line-height: 1;
      padding: 0;
      background-color: #fff;
    }
  }

  .tree-select__tree {
    padding: 4px 20px;
    font-weight: 400;
    &.tree-select__tree--radio {
      .el-tree-node.is-current > .el-tree-node__content {
        color: #000;
        font-weight: 700;
      }
    }
  }
  </style>
